package com.dona.imsidetector.db.dao;

import android.util.Log;

import com.dona.imsidetector.db.XUtilsManager;
import com.dona.imsidetector.db.entity.History;

import org.xutils.DbManager;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;

import java.util.Set;

public class HistoryDao {

    private static final String TAG = "HistoryDao";
    private static DbManager dbManager = XUtilsManager.getInstance().getDbManager();


    public static String add(Integer isp, Integer deviceId, Set<Integer> freqs) {
        History history = find(isp, deviceId);
        Log.e(TAG, "HistoryDao add: " + (history == null));
        try {
            if (history != null) {
                history.setFreqs(History.freqsToJson(freqs));
                Log.e(TAG, "update: " + history.toString());
                dbManager.update(history);
            } else {
                History h = new History(isp, deviceId, freqs);
                Log.e(TAG, "save: " + h.toString());
                dbManager.save(h);
            }
        } catch (DbException e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return null;
    }

    public static String clear() {
        try {
            dbManager.delete(History.class);
        } catch (DbException e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return null;
    }

    public static String delete(History history) {
        try {
            dbManager.delete(history);
        } catch (DbException e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return null;
    }

    public static History find(Integer isp, Integer deviceId) {
        try {
            WhereBuilder b = WhereBuilder.b();
            b.and("isp", "=", isp); //构造修改的条件
            b.and("deviceId", "=", deviceId);
            History history = dbManager.selector(History.class)
                    .where(b)
                    .findFirst();
            if (history != null) {
                Log.e(TAG, "isp: " + isp + " deviceId: " + deviceId + " HistoryDao find: " + history.toString());
            }
            return history;
        } catch (DbException e) {
            e.printStackTrace();
        }
        return null;
    }


}
